package utils

import (
	"github.com/nsqio/go-nsq"
	"errors"
	"bytes"
	"encoding/gob"
)

var g_NsqInstance *NsqUtil

type NsqUtil struct {
	producer *nsq.Producer
	ip       string //nsq服务地址
}

func (self *NsqUtil) Init() error {
	config := nsq.NewConfig()

	producer, err := nsq.NewProducer(self.ip, config)

	if err == nil {
		self.producer = producer
	}

	return err
}

func NsqUtilInit(ipStr string) error {
	if g_NsqInstance == nil {
		g_NsqInstance = &NsqUtil{ip: ipStr}

		return g_NsqInstance.Init()
	}

	return nil
}

func NsqPublishGobMessage(topicName string, e interface{}) error {

	if g_NsqInstance == nil || g_NsqInstance.producer == nil {
		return errors.New("not inited!")
	}

	//将数据gob序列化
	var buf bytes.Buffer
	enc := gob.NewEncoder(&buf)
	err := enc.Encode(e)
	if err != nil {
		return err
	}
	return g_NsqInstance.producer.Publish(topicName, buf.Bytes())
}